import 'package:dio/dio.dart';
import 'package:dio_log/interceptor/dio_log_interceptor.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutterapp/Base/UIComponent/LoadingConfig.dart';
import 'package:flutterapp/Base/net/TokenInterceptor.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import 'dart:convert' as convert;
class HttpManager {
  static final BaseOptions _options = BaseOptions(
    connectTimeout: 10 * 1000,
    receiveTimeout: 10 * 1000,

    /// 请求的Content-Type，默认值是"application/json; charset=utf-8".
    /// 如果您想以"application/x-www-form-urlencoded"格式编码请求数据,
    /// 可以设置此选项为 `Headers.formUrlEncodedContentType`,  这样[Dio]
    /// 就会自动编码请求体.
    contentType: Headers.jsonContentType,

    /// 默认值是 `JSON`, 当响应头中content-type为"application/json"时，dio 会自动将响应内容转化为json对象。
    responseType: ResponseType.json,

    /// `validateStatus` 决定http响应状态码是否被dio视为请求成功， 返回`validateStatus`
    ///  返回`true` , 请求结果就会按成功处理，否则会按失败处理.
//      ValidateStatus validateStatus;
  );
  static Dio _dio = Dio(_options);
  static const METHOD_POST = "POST";
  static const METHOD_GET = "GET";

  HttpManager() {
    _dio.interceptors.add(TokenInterceptor());
    _dio.interceptors.add(DioLogInterceptor());
    _dio.interceptors.add(PrettyDioLogger(
        requestHeader: false,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
        error: true,
        compact: true,
        maxWidth: 120));
  }

  Future get<T>(String url,
      {Map<String, dynamic> params,
      Map<String, dynamic> headers,
      bool showLoading = true}) {
    return fetch(url,
        method: METHOD_GET,
        params: params,
        headers: headers,
        showLoading: showLoading);
  }

  Future post<T>(String url,
      {var data, Map<String, dynamic> headers, bool showLoading = true}) {
    return fetch(url,
        method: METHOD_POST,
        data: convert.jsonEncode(data),
        headers: headers,
        showLoading: showLoading);
  }

  Future postForm<T>(String url,
      {Map<String, dynamic> data,
      Map<String, dynamic> headers,
      bool showLoading = true}) {
    return fetch(url,
        method: METHOD_POST,
        data: FormData.fromMap(data),
        headers: headers,
        isFormData: true,
        showLoading: showLoading);
  }

  Future fetch<T>(String url,
      {String method = METHOD_POST,
      var data,
      Map<String, dynamic> params,
      Map<String, dynamic> headers,
      bool isFormData = false,
      bool showLoading = true}) async {
    Response response;
    Options options = Options();
    options.method = method;
    if (isFormData) {
      options.contentType = Headers.formUrlEncodedContentType;
    }else{
      options.contentType=Headers.jsonContentType;
    }
    if (headers != null && headers.isNotEmpty) {
      options.headers.addAll(headers);
    }
    if (showLoading) {
      MyLoading.show();
    }
    try {
      response = await _dio.request(url,
          options: options, data: data, queryParameters: params);
    } catch (e) {
      print(e);
      Fluttertoast.showToast(msg:"$e");
      return Future.error(e);
    } finally {
      if (showLoading) {
        MyLoading.dismiss();
      }
    }

//    todo 请求成功状态的实现&判断自定义级别状态码
    if (response.statusCode == 200) {
      return Future.value(response.data["result"]);//result 为自定义字段
    } else {
      Fluttertoast.showToast(msg:"code:${response.statusCode}");
      return Future.error(new DioError());
    }
  }
}
